package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.util.ExcelReaderUtils;
import com.example.demo.util.ExcelWriterUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
public class HelloController {

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello World";
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 导出操作
        long startTime = System.currentTimeMillis();
        ExcelWriterUtils.writer(getStudentList(), "学生成绩表.xls", response);
        long endTime = System.currentTimeMillis();

        System.out.println(String.format("导出耗时%s秒", (endTime - startTime) / 1000));

    }

    @GetMapping("/test")
    @ResponseBody
    public List<Student> test() {
        List<Student> stuList;
        try {
            stuList = ExcelReaderUtils.parse(ResourceUtils.getFile("classpath:student.xlsx"), Student.class);
        } catch (Exception e) {
            e.printStackTrace();
            stuList = Arrays.asList();
        }
        return stuList;
    }

    private List<Student> getStudentList() {

        // 模拟 5 万条数据
        List<Student> stuList = new ArrayList<>(50000);
        Student stu;
        int sno = 10000;
        for (int i = 0; i < 50000; i++) {
            stu = new Student();
            stu.setSno(sno++);
            stu.setName("张三_" + stu.getSno());
            stu.setSex(i / 2 == 0 ? "男" : "女");
            stu.setBirthdayDate(new Date());
            stu.setScore((double) (int) (Math.random() * 100));
            stu.setBeMember( i / 2 == 0);
            stuList.add(stu);
        }
        return stuList;
    }
}
